export default {
  data() {
    return {
      codeOps: {
        countDownTime: consts.COUNT_DOWN_TIME,
        countdown: 0,

        firstTime: true,
        countdownTimer: undefined,
        codeError: '',
      },

      tDefaults: '获取验证码',
      tSending: '验证码已发送',
      tReSend: '重新获取验证码',
      sendingData: 'form',
      sendingCode: false,
      captchaStatus: false, //验证是否成功，
      showCaptcha: false, // 是否显示验证,
    };
  },

  computed: {
    codeBtnText() {
      if (this.sendingCode) {
        return `${this.tSending} ${this.codeOps.countdown}s`;
      } else if (this.codeOps.firstTime) {
        return this.tDefaults;
      } else {
        return this.tReSend;
      }
    }
  },


  mounted() {
    this.bindGet(this.codeApi, 'mobileData', {
      action:'getCode',
      sendingData: this.sendingData,
      beforeSend: (data) => {
        this.codeOps.codeError = '';

        return data;
      },
      afterSuccess: () => {
        this.$_countDown();
      },
      afterFail: ([result, data]) => {
        this.codeOps.codeError = data.message;
      }
    });
  },

  methods: {
    sendCode({
               formItem
             } = {}) {
      if (this.codeOps.countdown === 0) {
        // this.doGet({action: 'getCode', form: formItem});
        if (this.form[formItem]) {
          // 为了触发验证
          if(this.form[formItem] === '1' ){
            this.doGet({action: 'getCode'});
          }else {
            this.doGet({action: 'getCode', form: formItem});
          }
        }
        if (this.form[formItem]) {
          this.showCaptcha = true;
        }
      }
    },
// 验证码弹窗关闭后
    captchaClose() {
      this.captchaStatus = false;
      this.showCaptcha = false;
    },

    getResult(err, data) {
      this.captchaStatus = data ? !!data.validate : false;
      this.form.validate = data ? data.validate : "";
      this.captchaStatus ? this.doGet({ action: 'getCode'}) : null;
    },
    $_countDown() {
      this.codeOps.firstTime = false;
      this.sendingCode = true;
      this.codeOps.countdown = this.codeOps.countDownTime;
      this.codeOps.countdownTimer = setInterval(() => {
        if (this.codeOps.countdown > 1) {
          --this.codeOps.countdown;
        } else {
          this.codeOps.countdown = 0;
          this.sendingCode = false;
          clearInterval(this.codeOps.countdownTimer);
        }
      }, 1000);
    },
  }

};
